#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
管理员相关API路由
"""

from flask import Blueprint, request, jsonify
from models.admin import Admin
from models.user import User
from models.order import Order
from models.recharge import Recharge
from models.table import BilliardTable
from database import db
from utils.decorators import admin_required
from datetime import datetime, timedelta

admin_bp = Blueprint('admin', __name__)

@admin_bp.route('/dashboard', methods=['GET'])
@admin_required
def get_dashboard(admin):
    """获取仪表板数据"""
    try:
        # 用户统计
        total_users = User.query.count()
        new_users_today = User.query.filter(
            User.created_at >= datetime.now().date()
        ).count()
        
        # 订单统计
        total_orders = Order.query.count()
        orders_today = Order.query.filter(
            Order.created_at >= datetime.now().date()
        ).count()
        
        # 营收统计
        today_revenue = db.session.query(db.func.sum(Order.final_amount)).filter(
            Order.created_at >= datetime.now().date(),
            Order.payment_status == 'paid'
        ).scalar() or 0
        
        month_start = datetime.now().replace(day=1).date()
        month_revenue = db.session.query(db.func.sum(Order.final_amount)).filter(
            Order.created_at >= month_start,
            Order.payment_status == 'paid'
        ).scalar() or 0
        
        # 台球桌统计
        total_tables = BilliardTable.query.count()
        occupied_tables = BilliardTable.query.filter(
            BilliardTable.status == 'occupied'
        ).count()
        available_tables = BilliardTable.query.filter(
            BilliardTable.status == 'available'
        ).count()
        
        # 充值统计
        total_recharge = db.session.query(db.func.sum(Recharge.total_amount)).filter(
            Recharge.payment_status == 'paid'
        ).scalar() or 0
        
        # 最近7天数据
        seven_days_ago = datetime.now() - timedelta(days=7)
        daily_data = []
        
        for i in range(7):
            date = (datetime.now() - timedelta(days=6-i)).date()
            next_date = date + timedelta(days=1)
            
            daily_orders = Order.query.filter(
                Order.created_at >= date,
                Order.created_at < next_date
            ).count()
            
            daily_revenue = db.session.query(db.func.sum(Order.final_amount)).filter(
                Order.created_at >= date,
                Order.created_at < next_date,
                Order.payment_status == 'paid'
            ).scalar() or 0
            
            daily_data.append({
                'date': date.strftime('%m-%d'),
                'orders': daily_orders,
                'revenue': float(daily_revenue)
            })
        
        return jsonify({
            'success': True,
            'data': {
                'overview': {
                    'total_users': total_users,
                    'new_users_today': new_users_today,
                    'total_orders': total_orders,
                    'orders_today': orders_today,
                    'today_revenue': float(today_revenue),
                    'month_revenue': float(month_revenue),
                    'total_tables': total_tables,
                    'occupied_tables': occupied_tables,
                    'available_tables': available_tables,
                    'total_recharge': float(total_recharge)
                },
                'daily_data': daily_data,
                'table_utilization': round(occupied_tables / total_tables * 100, 2) if total_tables > 0 else 0
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取仪表板数据失败: {str(e)}'}), 500

@admin_bp.route('/profile', methods=['GET'])
@admin_required
def get_profile(admin):
    """获取管理员个人信息"""
    return jsonify({
        'success': True,
        'data': admin.to_dict()
    })

@admin_bp.route('/profile', methods=['PUT'])
@admin_required
def update_profile(admin):
    """更新管理员个人信息"""
    try:
        data = request.get_json()
        
        if 'name' in data:
            admin.name = data['name']
        if 'email' in data:
            admin.email = data['email']
        if 'phone' in data:
            admin.phone = data['phone']
        
        admin.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '个人信息更新成功',
            'data': admin.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新个人信息失败: {str(e)}'}), 500

@admin_bp.route('/change-password', methods=['PUT'])
@admin_required
def change_password(admin):
    """修改密码"""
    try:
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return jsonify({'success': False, 'message': '旧密码和新密码不能为空'}), 400
        
        if not admin.verify_password(old_password):
            return jsonify({'success': False, 'message': '旧密码错误'}), 400
        
        if len(new_password) < 6:
            return jsonify({'success': False, 'message': '新密码长度不能少于6位'}), 400
        
        admin.password = new_password
        admin.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '密码修改成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'修改密码失败: {str(e)}'}), 500